package com.kuhh.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kuhh.pojo.LoginHistory;
import com.kuhh.pojo.User;
import com.kuhh.service.ILoginHistoryService;
import com.kuhh.service.impl.LoginHistoryServiceImpl;
import com.kuhh.service.impl.UserServiceImpl;

/**
 * 登录提交
 * @author Administrator
 */
@WebServlet("/loginUrl")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		ILoginHistoryService loginHistoryService = new LoginHistoryServiceImpl();
		UserServiceImpl userService = new UserServiceImpl();
		String msg = "";
		String path = "/mainUrl";
		try {
			User user = userService.loginCheck(username, password);
			LoginHistory loginHistory = new LoginHistory();
			loginHistory.setUserId(user.getUserId());
			loginHistory.setIp(request.getRemoteAddr());
			loginHistory.setCreateTime(new Date());
			loginHistoryService.addLoginHistory(loginHistory);
			request.getSession().setAttribute("loginUser", user);
		} catch (Exception e) {
			e.printStackTrace();
			msg = "登录失败！"+e.getMessage();
			path = "/WEB-INF/pages/error.jsp";
			request.setAttribute("msg", msg);
		}
		request.getRequestDispatcher(path).forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
